//
//  SelfInformationViewCtrler.m
//  MIDI
//
//  Created by 千行时线 on 15/9/15.
//  Copyright (c) 2015年 QXSX. All rights reserved.
//

#import "SelfInformationViewCtrler.h"
#import "AppConfig.h"
#import "ChangeInforViewCtrl.h"
#import "UIViewController+Create.h"
#import "ChangeNickNameViewCtrler.h"
#import "ChangeMailViewCtrler.h"
#import "ChangeNameViewCtrler.h"
#import "ChangePhoneNumViewCtrler.h"
#import "ChangeNameViewCtrler.h"
#import "ChangeIDViewCtrler.h"
#import "ChangeIDViewCtrler.h"
#import "ChangePswViewCtrl.h"
#import "ChangeLocationViewCtrler.h"
#import "ChanageNationViewCtrler.h"
#import "SelfInfomationCell.h"
#import "APIAdress.h"
#import "UserDataSingleton.h"
#import "UIImageView+WebCache.h"
#import "CommFunc.h"
#import "MBProgressHUD+YC.h"
#import "QXNetWorkTool.h"
#import "SelfInfoModel.h"


#define MIDIIDFORMAT @"midiID:%s"

@interface SelfInformationViewCtrler ()<UITableViewDelegate , UITableViewDataSource , UITextFieldDelegate , QXNetWorkToolDelegate>
@property (weak, nonatomic) UIImageView *mainIconUIIamge;

@property (weak, nonatomic) UILabel *midiIDUILabel;

@property (weak , nonatomic) UITextField * nameTexfield;
@property (weak , nonatomic) UITextField * IDField;
@property (weak , nonatomic) UITextField * mailField;
@property (strong , nonatomic) QXNetWorkTool *netTool;
@property (strong , nonatomic) NSMutableDictionary *infoDic;

@property (weak, nonatomic) IBOutlet UITableView *myTableView;
@property (assign , nonatomic) BOOL isNameRight;
@property (assign , nonatomic) BOOL isIDNumRight;
@property (assign , nonatomic) BOOL isEmailRight;


@end

@implementation SelfInformationViewCtrler

- (void)viewDidLoad {
    [super viewDidLoad];
    self.myTableView.delegate = self;
    self.myTableView.dataSource = self;
    self.myTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.isNameRight = NO;
    self.isIDNumRight = NO;
    self.isEmailRight = NO;
    self.netTool = [[QXNetWorkTool alloc]init];
    self.netTool.QXNetWorkDelegate = self;
    self.infoDic = [[NSMutableDictionary alloc]init];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)didClick_CompleteInfomation:(id)sender
{
    [self.navigationController pushViewController:[ChangeInforViewCtrl create] animated:YES];
}
- (void)didClick_NickName:(id)sender
{
    [self.navigationController pushViewController:[ChangeNickNameViewCtrler create] animated:YES];
}
- (void)didClick_Mail:(id)sender
{
    [self.navigationController pushViewController:[ChangeMailViewCtrler create] animated:YES];
}
- (void)didClick_Location:(id)sender
{
    [self.navigationController pushViewController:[ChangeLocationViewCtrler create] animated:YES];
}
- (void)didClick_ChangePsw:(id)sender
{
    [self.navigationController pushViewController:[ChangePswViewCtrl create] animated:YES];
}
- (void)didClick_ChangePhoneNum:(id)sender
{
    [self.navigationController pushViewController:[ChangePhoneNumViewCtrler create] animated:YES];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self configNavigationItem];
    [self reqSelfInfo];
}


-(void) configNavigationItem
{
    [self.tabBarController configNavigationBarTintColor:UIColorRGBA(0, 0, 0, 1)];
    [self.navigationController.navigationBar setBarTintColor:MIDIColorOfNavigationBar];
    self.navigationController.navigationBar.barStyle = UIBarStyleBlack;
    self.navigationItem.title = @"个人信息";
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],UITextAttributeTextColor, [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:1.0],UITextAttributeTextShadowColor,[UIFont fontWithName:@"Hiragino Sans GB" size:18.0],UITextAttributeFont,nil]];
    
    [self configNavigationBackAction:^{
        
        [self.navigationController popViewControllerAnimated:YES];
    }];
    
    UIBarButtonItem *rightBar = [[UIBarButtonItem alloc] initWithTitle:@"保存" style:UIBarButtonItemStyleBordered target:self action:@selector(clickSave:)];
    UIFont *rightFont = [UIFont fontWithName:@"Hiragino Sans GB" size:13.0];
    UIColor *rightColor = UIColorRGBA(19, 208, 202, 1);
    
    NSDictionary * attributes = @{NSFontAttributeName:rightFont , NSForegroundColorAttributeName:rightColor };
    [rightBar setTitleTextAttributes:attributes forState:UIControlStateNormal];
    [self.navigationItem setRightBarButtonItem:rightBar];
    
    
}

-(void)clickSave:(id)sender
{
//    if(!self.isNameRight)
//    {
//        [MBProgressHUD showError:@"请输入姓名"];
//        return;
//    }
//    else if(!self.isIDNumRight)
//    {
//        [MBProgressHUD showError:@"请输入正确的身份证号"];
//        return;
//    }
//    else if(!self.isEmailRight)
//    {
//        [MBProgressHUD showError:@"请输入正确的email"];
//        return;
//    }
    
    NSMutableDictionary * dic = self.infoDic;
    [dic removeAllObjects];
    UserDataSingleton *userdata = [UserDataSingleton shareInstance];
    [dic setValue:self.nameTexfield.text forKey:@"real_name"];
    [dic setValue:userdata.user_id forKey:@"user_id"];
    [dic setValue:userdata.nickname forKey:@"nickname"];
    [dic setValue:self.mailField.text forKey:@"eamil"];
    [dic setValue:self.IDField.text forKey:@"id_card"];
    
    [dic setValue:userdata.province forKey:@"province"];
    [dic setValue:userdata.curCityId forKey:@"city"];
    [dic setValue:userdata.phone forKey:@"phone"];
    [dic setValue:userdata.nationality forKey:@"nationality"];
    [dic setValue:userdata.sex forKey:@"sex"];
    [dic setValue:userdata.birthday forKey:@"birthday"];
    [dic setValue:userdata.people forKey:@"people"];
    [dic setValue:userdata.head_img forKey:@"head_img"];
    [self.netTool GetDataFromServerWithPostMethodandInterfaceName:FillDetailInterface andParameter:@[dic] tag:1];
}

-(void)initUI
{
    self.mainIconUIIamge.userInteractionEnabled = YES;
    UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapIcoImage:)];
    [self.mainIconUIIamge addGestureRecognizer:tapGestureRecognizer];
}

-(void)tapIcoImage : (UITapGestureRecognizer *)gesture
{
    
}

#pragma mark tableView datasource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 587;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    SelfInfomationCell * cell = [SelfInfomationCell loadFromXib];
    [self configCell:cell];
    return cell;
}

#pragma mark - Table View Delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
}

-(void)configCell:(SelfInfomationCell*)cell
{
    self.mainIconUIIamge = cell.headIconImg;
    [self.mainIconUIIamge.layer setCornerRadius:self.mainIconUIIamge.frame.size.width/2];
    self.mainIconUIIamge.clipsToBounds = YES;
    self.mainIconUIIamge.contentMode = UIViewContentModeScaleAspectFill;
    self.midiIDUILabel = cell.accountLabel;
    self.nameTexfield = cell.nameField;
    self.IDField = cell.IDFeild;
    self.mailField = cell.mailField;
    self.nameTexfield.tag = 1;
    self.IDField.tag = 2;
    self.mailField.tag = 3;
    self.nameTexfield.delegate = self;
    self.IDField.delegate = self;
    self.mailField.delegate = self;
    
    
    UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tap)];
    
    [cell.headIconImg addGestureRecognizer:tapGestureRecognizer];
    
    [cell.changePwdBtn addTarget:self action:@selector(didClick_ChangePsw:) forControlEvents:UIControlEventTouchUpInside];
    [cell.changePhoneBtn addTarget:self action:@selector(didClick_ChangePhoneNum:) forControlEvents:UIControlEventTouchUpInside];
    [cell.completeSelfInfoBtn addTarget:self action:@selector(didClick_CompleteInfomation:) forControlEvents:UIControlEventTouchUpInside];
    UserDataSingleton *userdata = [UserDataSingleton shareInstance];
    if([userdata isLogin])
    {
        [self.midiIDUILabel setText:[@"midiID: " stringByAppendingString: userdata.midi_id]];
        NSString *headUrl = userdata.head_img;
        if(headUrl == nil || [headUrl isEqual:@""])
        {
            self.mainIconUIIamge.image = [UIImage imageNamed:@"ico_selfinfo_nonoe"];
        }
        else
        {
//            [self.mainIconUIIamge setImage:[[UIImage alloc]initWithData:[CommFunc getDecodedDataFromBase64String:headUrl]]];
            [self.mainIconUIIamge sd_setImageWithURL:[NSURL URLWithString:headUrl]];
        }
    }
}

-(void)tap
{

}

-(void)textFieldDidEndEditing:(UITextField *)textField
{
    if(textField.tag == 1)
    {
        if(textField.text == nil || [textField.text isEqual:@""])
        {
            [MBProgressHUD showError:@"请输入姓名"];
            self.isNameRight = NO;
            return;
        }
        self.isNameRight = YES;
    }
    else if(textField.tag == 2) //身份证
    {
        BOOL isRightIDNum = [CommFunc validateIDCardNumber:textField.text];
        if(!isRightIDNum)
        {
            [MBProgressHUD showError:@"请输入正确的身份证号"];
            self.isIDNumRight = NO;
            return;
        }
        self.isIDNumRight = YES;
    }
    else if(textField.tag == 3)//邮件
    {
        BOOL isRightEmail = [CommFunc isValidateEmail:textField.text];
        if(!isRightEmail)
        {
            self.isEmailRight = NO;
            [MBProgressHUD showError:@"请输入正确的email"];
            return;
        }
        self.isEmailRight = YES;
    }
}


#pragma mark  ----QXNetTool----------------
-(void)GetSuccessResponse:(id)Response andTag:(int)tag
{
    
    if(tag == 1)
    {
        [UserDataSingleton shareInstance].isSelfInfoChange = YES;
        UserDataSingleton *userdata = [UserDataSingleton shareInstance];
        //userdata.province = [self.infoDic objectForKey:@"province"];
        userdata.real_name = [self.infoDic objectForKey:@"real_name"];
        userdata.eamil = [self.infoDic objectForKey:@"eamil"];
        userdata.id_card = [self.infoDic objectForKey:@"id_card"];
        [self reqSelfInfo];
    }
    else if (tag == 2)
    {
        SelfInfoModel * data = nil;
        for(NSDictionary * dic in Response)
        {
            data = [SelfInfoModel MyModelWithDict:dic];
            break;
        }
        if(data == nil)
            return;
        UserDataSingleton *userdata = [UserDataSingleton shareInstance];
        userdata.isGotSelfInfo = YES;
        userdata.midi_id = data.midi_id;
        userdata.sex = data.sex;
        userdata.eamil = data.eamil;
        userdata.people = data.people;
        userdata.nationality = data.nationality;
        userdata.id_card = data.id_card;
        userdata.head_img = data.head_img;
        userdata.nickname = data.nickname;
        userdata.real_name = data.real_name;
        userdata.phone = data.phone;
        userdata.birthday = data.birthday;
        userdata.isSelfInfoChange = NO;
        [self.myTableView reloadData];
    }
    
}

-(void)GetFailResponse:(id)Response andTag:(int)tag
{
    
}

-(void)GetSuccessMessage:(id)message andTag:(int)tag
{
    
}


//请求个人数据
-(void)reqSelfInfo
{
    UserDataSingleton *userdata = [UserDataSingleton shareInstance];
    [self.netTool GetDataFromServerWithPostMethodandInterfaceName:GetSelfInfoInterface andParameter:@[@{@"user_id":userdata.user_id}] tag:2];
}

@end
